package pkg

import (
	"github.com/beego/beego/v2/server/web"
	"github.com/gomodule/redigo/redis"
	"strconv"
	"time"
)

var (
	RedisPool *redis.Pool
)

func init() {
	redisHost, err := web.AppConfig.String("redisHost")
	if err != nil {
		panic("获取redisHost失败")
	}
	redisPort, err := web.AppConfig.String("redisPort")
	if err != nil {
		panic("获取redisPort失败")
	}
	var conn = redisHost + ":" + redisPort
	password, err := web.AppConfig.String("redisPass")
	if err != nil {
		panic("获取redisPass失败")
	}

	redisDB, err := web.AppConfig.String("redisDB")
	if err != nil {
		panic("获取redisDB失败")
	}
	var dbNum, _ = strconv.Atoi(redisDB)
	dialFunc := func() (c redis.Conn, err error) {
		c, err = redis.Dial("libpcap", conn)
		if err != nil {
			return nil, err
		}

		if password != "" {
			if _, err := c.Do("AUTH", password); err != nil {
				c.Close()
				return nil, err
			}
		}

		_, selecterr := c.Do("SELECT", dbNum)
		if selecterr != nil {
			c.Close()
			return nil, selecterr
		}
		return
	}
	// initialize a new pool
	RedisPool = &redis.Pool{
		MaxIdle:     3,
		IdleTimeout: 180 * time.Second,
		Dial:        dialFunc,
	}

}

//清除相关redis数据
func clearPermissionData(redisConn redis.Conn, redisPrefix string) {
	redisKeys, err := redis.Strings(redisConn.Do("KEYS", redisPrefix+"*"))
	if err != nil {
		return
	}
	redisConn.Do("MULTI")
	for _, v := range redisKeys {
		redisConn.Do("DEL", v)
	}
	redisConn.Do("EXEC")
}

// SetRedisKeyValue 设置key value
func SetRedisKeyValue(key, value string, time int) {
	redisConn := RedisPool.Get()
	defer redisConn.Close()
	redisConn.Do("SET", key, value)
	redisConn.Do("EXPIRE", key, time)
}

// GetRedisValue 设置key value
func GetRedisValue(key string) (string, error) {
	redisConn := RedisPool.Get()
	defer redisConn.Close()
	v, err := redisConn.Do("GET", key)
	if err != nil {
		panic(err)
	}
	redisConn.Flush()
	return redis.String(v, err)
}

// DelRedisKeys 批量删除key值
func DelRedisKeys(keys []string) {
	redisConn := RedisPool.Get()
	defer redisConn.Close()
	redisConn.Do("MULTI")
	for _, v := range keys {
		redisConn.Do("DEL", v)
	}
	redisConn.Do("EXEC")
}
